package org.example.mouse;

import java.awt.Robot;
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Point;

public class MouseController {
    private Robot robot;

    public MouseController() {
        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用相对移动实现绝对移动
     * @param targetX 目标x坐标
     * @param targetY 目标y坐标
     * @param duration 移动时间(毫秒)
     */
    public void moveTo(int targetX, int targetY, int duration) {
        Point current = MouseInfo.getPointerInfo().getLocation();
        int dx = targetX - current.x;
        int dy = targetY - current.y;

        smoothMoveRelative(dx, dy, duration);
    }

    /**
     * 平滑相对移动
     * @param dx x方向移动距离
     * @param dy y方向移动距离
     * @param duration 移动时间(毫秒)
     */
    public void smoothMoveRelative(int dx, int dy, int duration) {
        Point start = MouseInfo.getPointerInfo().getLocation();
        int steps = calculateSteps(dx, dy, duration);

        for (int i = 1; i <= steps; i++) {
            double progress = (double) i / steps;
            progress = easeOutQuad(progress); // 使用缓动函数

            int currentX = start.x + (int)(dx * progress);
            int currentY = start.y + (int)(dy * progress);

            // 使用相对移动实现
            Point now = MouseInfo.getPointerInfo().getLocation();
            int relX = currentX - now.x;
            int relY = currentY - now.y;

            if (relX != 0 || relY != 0) {
                robot.mouseMove(now.x + relX, now.y + relY);
            }

            try {
                Thread.sleep(duration / steps);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 确保最终位置准确
        robot.mouseMove(start.x + dx, start.y + dy);
    }

    /**
     * 根据移动距离和时间计算步数
     */
    private int calculateSteps(int dx, int dy, int duration) {
        double distance = Math.sqrt(dx * dx + dy * dy);
        // 每像素至少0.5毫秒，最多20步
        return (int) Math.min(Math.max(distance * 0.5, 5), Math.max(duration / 10, 20));
    }

    /**
     * 二次缓动函数 - 平滑减速
     */
    private double easeOutQuad(double t) {
        return t * (2 - t);
    }

    public static void main(String[] args) {
        MouseController controller = new MouseController();

        // 使用相对移动实现绝对移动
        controller.moveTo(500, 300, 1000); // 移动到(500,300)，耗时1000ms

//        // 等待2秒
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//        // 再次移动
//        controller.moveTo(800, 400, 1500); // 移动到(800,400)，耗时1500ms
    }
}